package org.frank.blockchain.p2p.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.SneakyThrows;

public class ManagerServer {
    protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2;
    Integer port = null;

    public static Channel mainChannel;

    public ManagerServer() {

    }
    public ManagerServer(Integer port) {
        this.port = port;
    }

    @SneakyThrows
    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new CommandDecoder(), new ManagerServerHandler());
//                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024*1024, Unpooled.wrappedBuffer(new byte[] {'\0'})));
//                            ch.pipeline().addLast(new JsonDecoder());
                        }
                    });
            ChannelFuture f = bootstrap.bind(port).sync();
            mainChannel = f.channel();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }


}
